/**
 * Copyright (c) 2016-2019 优博信息科技 All rights reserved.
 *
 * https://www.jnyoubo.com
 *
 * 版权所有，侵权必究！
 */

package com.youbo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbo.common.utils.RedisUtils;
import com.youbo.service.TokenService;
import com.youbo.dao.TokenDao;
import com.youbo.entity.TokenEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;


@Service("tokenService")
public class TokenServiceImpl extends ServiceImpl<TokenDao, TokenEntity> implements TokenService {
	/**
	 * 12小时后过期
	 */
	private final static int EXPIRE = 3600 * 24;

	@Autowired
	private RedisUtils redisUtils;


	@Override
	public TokenEntity queryByToken(String token,Integer tokenType) {
		TokenEntity tokenEntity=redisUtils.get(RedisUtils.MY_TOKEN+token,TokenEntity.class);
		if(null!=tokenEntity){
			return tokenEntity;
		}
		return this.getOne(new QueryWrapper<TokenEntity>().eq("token", token).eq("token_type", tokenType));
	}

	@Override
	public TokenEntity queryByToken(Long userId, Integer tokenType) {
		return this.getOne(new QueryWrapper<TokenEntity>().eq("user_id", userId).eq("token_type", tokenType));

	}

	@Override
	public TokenEntity createToken(long userId,Integer tokenType) {
		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 1000);

		//生成token
		String token = generateToken();

		//保存或更新用户toke
		TokenEntity tokenEntity=queryByToken(userId,tokenType);
		if(null==tokenEntity){
			tokenEntity=new TokenEntity();
		}
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		tokenEntity.setTokenType(tokenType);
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(expireTime);

		if(null!=tokenEntity){
			this.updateById(tokenEntity);
		}else{
			this.save(tokenEntity);
		}

		redisUtils.set(RedisUtils.MY_TOKEN+token,tokenEntity,(60 * 60 * 24 * 1)); // 一天过期

		return tokenEntity;
	}

	@Override
	public void expireToken(TokenEntity tokenEntity){
		Date now = new Date();
		tokenEntity.setUpdateTime(now);
		tokenEntity.setExpireTime(now);
		this.saveOrUpdate(tokenEntity);

		redisUtils.delete(RedisUtils.MY_TOKEN+tokenEntity.getToken());

	}

	private String generateToken(){
		return UUID.randomUUID().toString().replace("-", "");
	}
}
